import base64
import datetime
from django.core.files.uploadedfile import SimpleUploadedFile
from rest_framework import serializers
from Login.models import user
from Login.service.jwt import create_token, JWTQueryParamsAuthentication
from rest_framework.response import Response
from rest_framework.views import APIView
from Login.service import login, verify
from Login.service.serializers import RegisterSerializer, alter_passwordSerializer, alterInformationSerializer, \
    UserSerializer, changeAvatarSerializer
from Login.utils.encrpty import md5


# Create your views here.

class RegisterView(APIView):
    """用户注册"""
    authentication_classes = []  # 取消全局认证

    def post(self, request, *args, **kwargs):
        try:
            # print(request.data)
            serializer = RegisterSerializer(data=request.data, many=False)  # 只是一个对象，不能用many=True
            if serializer.is_valid():
                verify_password = serializer.validated_data.pop('verify_password')
                password = serializer.validated_data.get('password')
                # email = serializer.validated_data.get('email')
                serializer.validated_data.pop('code')
                if password != verify_password:
                    raise serializers.ValidationError("两次密码输入不一致，请重新输入")
                serializer.save()
                # print("-" * 90)
                # makeCodeBeInvalid(email=email)
                # 由于这里没有设置jwt，故前端设置时应该写成用户注册后跳转到登录页面
                return Response({'code': 200, 'msg': '注册成功'})
            return Response({'code': 404, 'msg': '注册失败', 'data': serializer.errors})
        except Exception as e:
            return Response({'code': 404, 'msg': e})


class LoginView(APIView):
    """用户登录"""
    authentication_classes = []  # 取消全局认证

    def post(self, request, *args, **kwargs):
        try:
            email = request.data.get('email')
            password = request.data.get('password')
            user_obj = login.userLogin(email=email, password=md5(password))
            # print(user_obj)
            if user_obj.get("msg") == "登录成功":
                payload = {
                    'user_id': user_obj["data"].get('user_id'),  # 自定义用户ID
                    'username': user_obj["data"].get('username'),  # 自定义用户名
                    'exp': datetime.datetime.utcnow() + datetime.timedelta(days=20),  # 设置超时时间，暂时设置为20天
                }
                # print(user_obj["data"].get('user_id'))
                # print(user_obj["data"].get('username'))
                jwt_token = create_token(payload=payload)
                msg = user_obj.get("msg")
                return Response({'code': 200, 'msg': msg, 'token': jwt_token})
            else:
                return Response({'code': 404, 'msg': user_obj.get("msg")})
        except Exception as e:
            return Response({'code': 404, 'msg': str(e)})


# 发送验证码
class sendCodeView(APIView):
    authentication_classes = []  # 取消全局认证

    def post(self, request):
        try:
            email = request.data.get('email')
            # print(email)
            if not email:
                return Response({'code': 404, 'msg': "请填写邮箱地址"})
            msg = verify.sendMessageByEmail(email=email)
            if msg == "验证码发送成功":
                return Response({'code': 200, 'msg': msg})
            elif msg == "请不要一分钟之内连续获取两次验证码":
                return Response({'code': 404, 'msg': msg})
            else:
                return Response({'code': 404, 'msg': msg})
        except Exception as e:
            return Response({'code': 404, 'msg': str(e)})


# 忘记密码后重置密码(登录后)
class alterPasswordView(APIView):
    def post(self, request):
        try:
            serializer = alter_passwordSerializer(data=request.data)
            if serializer.is_valid():
                # 替换密码
                User = user.objects.filter(user_id=request.user.get("user_id")).first()  # 注意request.user是字典
                if not User:
                    return Response({'code': 404, 'msg': "用户不存在"})
                # print(request.user)
                User.password = serializer.validated_data.get("password_confirm", None)
                User.save()
                return Response({'code': 200, 'msg': '重置密码成功'})
            return Response({'code': 404, 'msg': serializer.errors})
        except Exception as e:
            return Response({'code': 404, 'msg': str(e)})


# 修改个人信息
class alterInformationView(APIView):

    def post(self, request):
        try:
            serializer = alterInformationSerializer(data=request.data)
            if serializer.is_valid():
                User = user.objects.filter(user_id=request.user.get("user_id")).first()
                if not User:
                    return Response({"code": 404, "msg": "用户不存在"})
                # 修改前先做判断，传入不为空修改，为空跳过该字段
                information = serializer.validated_data.get("information", None)
                if information:
                    User.information = information
                username = serializer.validated_data.get("username", None)
                if username:
                    User.username = username
                email = serializer.validated_data.get("email", None)
                if email:
                    User.email = email
                # phone = serializer.validated_data.get("phone", None)
                # if phone:
                #     User.phone = phone
                birthday = serializer.validated_data.get("birthday", None)
                if birthday:
                    User.birthday = birthday
                province = serializer.validated_data.get("province", None)
                if province:
                    User.province = province
                city = serializer.validated_data.get("city", None)
                if city:
                    User.city = city
                country = serializer.validated_data.get("country", None)
                if country:
                    User.country = country
                gender = serializer.validated_data.get("gender", None)
                if gender:
                    User.gender = gender
                User.save()
                return Response({'code': 200, 'msg': '修改个人信息成功'})
            return Response({'code': 404, 'msg': serializer.errors})
        except Exception as e:  # 捕获与处理异常
            return Response({'code': 404, 'msg': f"系统错误{e}"})


# 登录前忘记密码
class LoginAlterPasswordView(APIView):
    authentication_classes = []  # 取消全局认证

    @staticmethod
    def post(request):
        try:
            serializer = UserSerializer(data=request.data)
            if serializer.is_valid():
                email = serializer.validated_data.get("email", None)
                User = user.objects.filter(email=email).first()
                if not User:
                    return Response({'code': 404, 'msg': '用户不存在'})
                User.password = serializer.validated_data.get("password", None)
                User.save()
                return Response({'code': 200, 'msg': '修改密码成功'})
            return Response({'code': 404, 'msg': serializer.errors})
        except Exception as e:
            return Response({'code': 404, 'msg': "系统错误"})


# 上传头像
class changeAvatarView(APIView):

    def post(self, request):
        try:
            avatar_base64 = request.data.get('avatar')
            _, base64_str = avatar_base64.split('base64,')

            # 解码图像数据
            image_data = base64.b64decode(base64_str)
            # 创建一个Django支持的uploadedFile对象
            avatar_uploaded_file = SimpleUploadedFile(
                name='avatar.jpg',
                content=image_data,
                content_type='image/jpeg'
            )
            # 创建包含文件对象的请求数据
            request_data_with_file = {'avatar': avatar_uploaded_file}
            serializer = changeAvatarSerializer(data=request_data_with_file)
            if serializer.is_valid():
                User = user.objects.filter(user_id=request.user.get("user_id")).first()
                if not User:
                    return Response({"code": 404, "msg": "用户不存在"})
                if User.avatar:
                    User.avatar.delete()
                # 保存新上传的头像文件到用户记录中
                User.avatar = serializer.validated_data['avatar']
                User.save()
                avatar_url = User.avatar.url
                return Response({'code': 200, 'msg': '更改头像成功', 'data': avatar_url})
            else:
                return Response({'code': 404, 'msg': '更改头像失败'})
        except Exception as e:
            return Response({'code': 404, 'msg': f"系统错误:{e}"})
